package com.hysf.controller;


import com.hysf.entity.User;

import com.hysf.service.UserService;
import com.hysf.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class UserController extends Base {

    private UserService userService = new UserServiceImpl();

    private UserService userService2 = new UserServiceImpl();

    /**
     *
     * @Description:
     *
     * @Author: 石涛
     * @Date: 2024/4/9 10:51
     **/
    protected void registerfiler(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取请求参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String email = req.getParameter("email");
        String gender = req.getParameter("gender");
        // 检查用户名是否可用

        if (userService.existsUserName(username)) {
            System.out.println("用户名【 " + username + "】 不可用");
            // 重新跳回到注册页面
            req.getRequestDispatcher("/register.jsp").forward(req, resp);
        } else {
            Integer state = 1;
            // 表示可用
            // 调用userService里面的注册方法
            userService.registerUser(new User(null, username, password, email, gender, null, null, null, state));
            // 跳转到注册成功页面
            req.setAttribute("username",username);
            req.getRequestDispatcher("/register_success.jsp").forward(req, resp);
        }
    }
    /**
     *
     * @Description:
     *
     * @Author: 石涛
     * @Date: 2024/4/9 10:53
     **/

    protected void loginfiler(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取请求参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        User login = userService2.login(username, password);
        System.out.println(login);

        if (login!=null) {
            HttpSession session = req.getSession();
            session.setAttribute("username",username);
            req.getRequestDispatcher("/login_success.jsp").forward(req, resp);
        } else {
            System.out.println("用户名或密码错误");
            req.getRequestDispatcher("/login.jsp").forward(req, resp);
        }

    }
}